﻿using MeetingRoomBooking.Domain.Entities;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace MeetingRoomBooking.Infrastructure.Data;
public static class InitialiserExtensions
{
    public static async Task InitialiseDatabaseAsync(this WebApplication app)
    {
        using var scope = app.Services.CreateScope();

        var initialiser = scope.ServiceProvider.GetRequiredService<ApplicationDbContextInitialiser>();

        await initialiser.InitialiseAsync();

        await initialiser.SeedAsync();
    }
}

public class ApplicationDbContextInitialiser
{
    private readonly ILogger<ApplicationDbContextInitialiser> _logger;
    private readonly ApplicationDbContext _context;   

    public ApplicationDbContextInitialiser(ILogger<ApplicationDbContextInitialiser> logger, ApplicationDbContext context)
    {
        _logger = logger;
        _context = context;      
    }

    public async Task InitialiseAsync()
    {
        try
        {
            await _context.Database.MigrateAsync();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "An error occurred while initialising the database.");
            throw;
        }
    }

    public async Task SeedAsync()
    {
        try
        {
            await TrySeedAsync();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "An error occurred while seeding the database.");
            throw;
        }
    }

    public async Task TrySeedAsync()
    {
        var now = DateTime.Now;
        User administrator = new() { UserName = "michael", Password = "123", Email = "xu@shilin.com", Role = "Admin",LastModified= now,Created=now };
        User user = new() { UserName = "Xu Shilin", Password = "123", Email = "michael@qq.com", Role = "User" };
        if (!_context.Users.Any())
        {
            _context.Add(administrator);
            _context.Add(user);
            await _context.SaveChangesAsync();
        }

        if (!_context.Rooms.Any())
        {
            _context.Add(new Room { Name = "Room1", Capacity = 10, Description = "There are TV, white board" });
            _context.Add(new Room { Name = "Room2", Capacity = 4, Description = "There are TV, white board" });
            _context.Add(new Room { Name = "Room3", Capacity = 5, Description = "There are TV, white board" });
            _context.Add(new Room { Name = "Room4", Capacity = 5, Description = "There are TV, white board" });
            await _context.SaveChangesAsync();
        }
    }   
}
